package com.kevin.util;

import org.icepdf.core.pobjects.Document;
import org.icepdf.core.pobjects.Page;
import org.icepdf.core.util.GraphicsRenderingHints;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

public class PdfUtil {
    private static final Logger logger = LoggerFactory.getLogger(PdfUtil.class);

    public static void main(String[] args) throws Exception {
        String filePath = "C:\\Users\\kevin\\Desktop\\测试\\Test.pdf";
        String desDirPath = "C:\\Users\\kevin\\Desktop\\测试\\icepdf";

        pdf2jpg(filePath, desDirPath);
    }

    /**
     * pdf转换jpg
     * @param filePath  源文件绝对路径
     * @param desDir    目标文件夹绝对路径，用于存放转换后的jpg
     * @return          转换后的jpg绝对路径列表
     */
    public static List<String> pdf2jpg(String filePath, String desDir) throws Exception {
        Path sourcePath = Paths.get(filePath);
        if (Files.notExists(sourcePath)) {
            throw new FileNotFoundException(filePath);
        }
        String filename = filePath.substring(filePath.lastIndexOf(File.separator) + 1,
                filePath.lastIndexOf("."));
        Path desDirPath = Paths.get(desDir);

        long start = System.currentTimeMillis();

        Document document = new Document();
        document.setFile(filePath);
        float scale = 2.5f;     //缩放比例，值越大，图片越清晰，图片越大
        float rotation = 0f;    //旋转角度

        String desFilePath;
        List<DesPage> desPages = new ArrayList<>();
        List<String> desFilePaths = new ArrayList<>();
        int pageCount = document.getNumberOfPages();
        for (int i = 0; i < pageCount; i++) {
            desFilePath = desDirPath + File.separator + filename + "_" + i + ".jpg";
            desFilePaths.add(desFilePath);
            desPages.add(new DesPage(i, desFilePath));
        }

        desPages.parallelStream().forEach(desPage -> {
            try {
                BufferedImage image = (BufferedImage) document.getPageImage(desPage.getPageNum(), GraphicsRenderingHints.SCREEN,
                        Page.BOUNDARY_CROPBOX, rotation, scale);
                ImageIO.write(image, "JPEG", new File(desPage.getFilePath()));
                image.flush();
            } catch (Exception e) {
                logger.error("pdf转jpg失败, filePath: {}", filePath);
                throw new RuntimeException(e);
            }
        });
        document.dispose();

        logger.info("pdf2jpg耗时" + (System.currentTimeMillis() - start) + "ms");
        return desFilePaths;
    }

    private static class DesPage {
        private int pageNum;
        private String filePath;

        public DesPage(int pageNum, String filePath) {
            this.pageNum = pageNum;
            this.filePath = filePath;
        }

        public int getPageNum() {
            return pageNum;
        }

        public void setPageNum(int pageNum) {
            this.pageNum = pageNum;
        }

        public String getFilePath() {
            return filePath;
        }

        public void setFilePath(String filePath) {
            this.filePath = filePath;
        }
    }
}
